package com.cxs.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@EnableWebSecurity  // 开启WebSecurity
// prePostEnabled = true 会解锁 @PreAuthorize 和 @PostAuthorize 两个注解。
// @PreAuthorize 注解会在方法执行前进行验证，而 @PostAuthorize 注解会在方法执行后进行验证。
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 登陆成功处理类
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    // 登录失败处理类
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Autowired
    private CaptchaFilter captchaFilter;

//    @Autowired
//    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    JwtLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Autowired
    UserDetailServiceImpl userDetailsService;

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 白名单
    private static final String[] URL_WHITELIST = {
        "/login", "/logout", "/captcha", "/favicon.ico","/test/**"
    };

    // 授权方法，配置权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //
        http.cors()
            .and().csrf().disable();

        // 登录配置
        http.formLogin()
                .loginProcessingUrl("/login")
//                .usernameParameter("username")
//                .passwordParameter("password")
                .successHandler(loginSuccessHandler)   // 配置登录成功的处理器
                .failureHandler(loginFailureHandler);   // 配置登录失败的处理器
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(jwtLogoutSuccessHandler);

        // 禁用session
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);  // session策略，不生成session

        // 配置拦截规则
        http
                .authorizeRequests()
                // 配置白名单，不需要拦截
                .antMatchers(URL_WHITELIST).permitAll()
                .antMatchers(HttpMethod.POST, "/perms").permitAll()
                // antMatchers中的参数是permission中的path，hasAnyRole中的参数是role中的code
//                .antMatchers(new String[]{ "/test" }).hasAnyRole(new String[]{ "admin", "normal" })
//                .antMatchers(new String[]{ "/pass" }).hasAnyRole(new String[]{ "admin"})
//                // 任何请求都需要认证后才能访问，如果不配置，则所有请求都无需认证就能访问
                .anyRequest().authenticated();

        // 配置自定义过滤器
        http
                .exceptionHandling()
//                .accessDeniedHandler(jwtAccessDeniedHandler)
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)  // 配置认证异常处理器
                .and()
                .addFilter(jwtAuthenticationFilter())  // jwt认证过滤器
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class); // 登录验证码校验过滤器

    }

    // 认证方法，用于身份认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //
        auth.userDetailsService(userDetailsService);
    }
}
